package com.jihu.leetcode.arrays;

import java.util.HashMap;
import java.util.Map;

/**
 * leetcode 1.两数之和
 * @author jihu
 * @date 2021/8/23
 */
public class TwoSum {

    //方法一：暴力法，穷举所有两数组合
    public int[] towSum1(int[] nums,int target){
        for (int i = 0; i < nums.length; i++) {
            for (int j = i+1; j < nums.length; j++) {
                if(nums[i]+nums[j] == target){
                    return new int[]{i,j};
                }
            }
        }
        throw new IllegalArgumentException("no solution");
    }

    //方法二：哈希表保存所有数的信息
    public int[] towSum2(int[] nums,int target){
        //定义一个哈希表
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i],i);
        }

        for (int i = 0; i < nums.length; i++) {
            int targetNum = target-nums[i];
            if(map.containsKey(targetNum) && map.get(targetNum) != i){
                return new int[]{i,map.get(targetNum)};
            }
        }
        throw new IllegalArgumentException("no solution");

    }

    public int[] towSum(int[] nums,int target) {

        //定义一个哈希表
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int targetNum = target-nums[i];
            if(map.containsKey(targetNum) && map.get(targetNum) != i){
                return new int[]{i,map.get(targetNum)};
            }
            map.put(nums[i],i);
        }
        throw new IllegalArgumentException("no solution");
    }

        public static void main(String[] args) {
        int[] input = new int[]{2,7,11,15};
        int target = 9;
        TwoSum towSum = new TwoSum();
        int[] ints = towSum.towSum(input, target);
        for (int num : ints) {
            System.out.println(input[num]);
        }
    }

}
